package com.steamedfish.auctionitemserver.service.elasticsearch;


import com.steamedfish.auctionitemserver.entiry.AuctionItemImage;
import com.steamedfish.auctionitemserver.model.AuctionItemModel;
import com.steamedfish.auctionitemserver.utils.ConvertUtils;
import com.steamedfish.auctionitemserver.utils.LocalDateTimeUtils;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class ElasticSearchService {

    private Integer DEFAULT_PAGE_INDEX = 0;

    private Integer DEFAULT_PAGE_SIZE = 2;

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    public SearchHits<AuctionItemModel> searchByKey(String searchString,String pageIndex,String pageSize) {
        //查询搜索结果
        NativeSearchQuery query = new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.multiMatchQuery(searchString, "description", "name"))
//                .withQuery(QueryBuilders.matchPhraseQuery("deleted", 0))
                .withPageable(PageRequest.of(StringUtils.isNotBlank(pageIndex)?Integer.parseInt(pageIndex):DEFAULT_PAGE_INDEX, StringUtils.isNotBlank(pageSize)?Integer.parseInt(pageSize):DEFAULT_PAGE_SIZE))
                .withHighlightBuilder(new HighlightBuilder().field("name").preTags("<span style='color:red'>").postTags("</span>"))
                .withSort(SortBuilders.fieldSort("createTime").order(SortOrder.DESC))
                .build();

        NativeSearchQuery queryAll = new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.matchAllQuery())
//                .withQuery(QueryBuilders.matchPhraseQuery("deleted", 0))
                .withPageable(PageRequest.of(StringUtils.isNotBlank(pageIndex)?Integer.parseInt(pageIndex):DEFAULT_PAGE_INDEX, StringUtils.isNotBlank(pageSize)?Integer.parseInt(pageSize):DEFAULT_PAGE_SIZE))
                .withHighlightBuilder(new HighlightBuilder().field("name").preTags("<span style='color:red'>").postTags("</span>"))
                .withSort(SortBuilders.fieldSort("createTime").order(SortOrder.DESC))
                .build();

        SearchHits<AuctionItemModel> searchHits = elasticsearchRestTemplate.search(StringUtils.isNotBlank(searchString)?query:queryAll, AuctionItemModel.class, IndexCoordinates.of("auction_item"));


        searchHits.getSearchHits().forEach(e -> {
            if (StringUtils.isNotEmpty(e.getContent().getItemImageId()) && !e.getContent().getDeleted().equals("1")) {

                //查询image数据
                NativeSearchQuery imageQuery = new NativeSearchQueryBuilder()
                        .withQuery(QueryBuilders.matchPhraseQuery("deleted", 0))
                        .withQuery(QueryBuilders.matchPhraseQuery("itemImageId", e.getContent().getItemImageId()))
                        .build();
                SearchHits<AuctionItemImage> searchHitsImage = elasticsearchRestTemplate.search(imageQuery, AuctionItemImage.class, IndexCoordinates.of("auction_item_image"));

                //将image放入model中
                List<String> iamgeUrls = new ArrayList<>();
                searchHitsImage.getSearchHits().forEach(image -> {
                    iamgeUrls.add(image.getContent().getImage());
                });

                String[] urls = ConvertUtils.covertListToArray(iamgeUrls);
                e.getContent().setUrls(urls);
            }
        });

        return searchHits;
    }

    public SearchHits<AuctionItemModel> searchByKey(String searchString){
        return this.searchByKey(searchString, null, null);
    }


    public List<AuctionItemModel> getAuctionItemModelList(SearchHits<AuctionItemModel> searchHits){


        List<AuctionItemModel> itemModelList = new ArrayList<>();
        searchHits.getSearchHits().forEach(e -> {

            AuctionItemModel auctionItemModel = e.getContent();
            auctionItemModel.setCreateTime(LocalDateTimeUtils.utcPlus8(auctionItemModel.getCreateTime()));
            auctionItemModel.setAuctionTime(LocalDateTimeUtils.utcPlus8(auctionItemModel.getAuctionTime()));
            auctionItemModel.setEndTime(LocalDateTimeUtils.utcPlus8(auctionItemModel.getEndTime()));

            itemModelList.add(auctionItemModel);
        });

        return itemModelList;
    }


    public AuctionItemModel getAuctionModelById(String id) {
        //构造请求
        NativeSearchQuery query = new NativeSearchQueryBuilder()
                //构造查询条件
                .withQuery(QueryBuilders.matchPhraseQuery("id", id))
                .build();
        //发起请求查询商品信息
        SearchHits<AuctionItemModel> searchHits = elasticsearchRestTemplate.search(query, AuctionItemModel.class, IndexCoordinates.of("auction_item"));

        //获取图片
        String imageID = null;
        try {
            imageID = searchHits.getSearchHit(0).getContent().getItemImageId();
        } catch (Exception e) {
            throw new RuntimeException("没有图片");
        }
        NativeSearchQuery imageQuery = new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.matchPhraseQuery("deleted", 0))
                .withQuery(QueryBuilders.matchPhraseQuery("itemImageId", imageID))
                .build();
        SearchHits<AuctionItemImage> searchHitsImage = elasticsearchRestTemplate.search(imageQuery, AuctionItemImage.class, IndexCoordinates.of("auction_item_image"));
        String[] urls = new String[searchHitsImage.getSearchHits().size()];
        for (int i = 0; i < searchHitsImage.getSearchHits().size(); i++) {
            String url = searchHitsImage.getSearchHit(i).getContent().getImage();
            urls[i] = url;
        }



        AuctionItemModel auctionItemModel = null;
        try {
            if (searchHits.getSearchHits().get(0).getContent().getDeleted().equals("0")) {
                auctionItemModel = searchHits.getSearchHits().get(0).getContent();
                auctionItemModel.setUrls(urls);
            }
        } catch (Exception e) {
            throw new RuntimeException("商品id为：" + id + "的拍品不存在");
        }


        auctionItemModel.setCreateTime(LocalDateTimeUtils.utcPlus8(auctionItemModel.getCreateTime()));
        auctionItemModel.setAuctionTime(LocalDateTimeUtils.utcPlus8(auctionItemModel.getAuctionTime()));
        auctionItemModel.setEndTime(LocalDateTimeUtils.utcPlus8(auctionItemModel.getEndTime()));

        return auctionItemModel;
    }





}